package com.itheima.web.controller;

import com.alibaba.fastjson.JSON;
import com.itheima.service.front.ExamService;
import com.itheima.service.front.MemberService;
import com.itheima.service.front.impl.ExamServiceImpl;
import com.itheima.service.front.impl.MemberServiceImpl;

import javax.servlet.ServletException;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.io.IOException;
import java.lang.reflect.InvocationTargetException;
import java.lang.reflect.Method;

/**
 * @program: mm_exam
 * @description:
 * @author: zhanghz001
 * @create: 2020-10-18 20:18
 **/
public class BaseServlet extends HttpServlet {
    public MemberService memberService;
    public ExamService examService;

    public <T> T getData(HttpServletRequest req, Class<T> clazz) throws IOException {
        return JSON.parseObject(req.getInputStream(), clazz);
    }

    public void returnData(HttpServletResponse resp, Result result) throws IOException {
        //返回结果
        resp.setContentType("application/json;charset=utf-8");
        JSON.writeJSONString(resp.getOutputStream(), result);
    }

    @Override
    public void init() throws ServletException {
        memberService = new MemberServiceImpl();
        examService = new ExamServiceImpl();
    }

    @Override
    protected void doGet(HttpServletRequest req, HttpServletResponse resp) throws ServletException, IOException {
        String uri = req.getRequestURI();
        int index = uri.lastIndexOf("/");
        String methodName = uri.substring(index + 1);

        Class clazz = this.getClass();
        Method method = null;
        try {
            method = clazz.getMethod(methodName, HttpServletRequest.class, HttpServletResponse.class);
            Result result = (Result) method.invoke(this, req, resp);
            returnData(resp, result);
        } catch (NoSuchMethodException e) {
            e.printStackTrace();
        } catch (IllegalAccessException e) {
            e.printStackTrace();
        } catch (InvocationTargetException e) {
            e.printStackTrace();
        }
    }

    @Override
    protected void doPost(HttpServletRequest req, HttpServletResponse resp) throws ServletException, IOException {
        doGet(req, resp);
    }
}
